<template>
    <el-dialog v-model="visible" title="重命名" width="30%" :close-on-click-modal="false">
        <el-form ref="formRef" :model="fileProps.record" :rules="rules" label-width="80px">
            <el-form-item label="文件名" prop="name">
                <el-input v-model="fileProps.record.name" :disabled="fileProps.disabled" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="handleSubmit">提交</el-button>
                <el-button @click="onClose">取消</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>
</template>
<script setup lang="ts">
import { fileAPI, SysFile } from "@/api";
import { ref, reactive } from "vue"; // 引入 ref、reactive
import { FormOptEnum } from "@/enums"; // 引入 FormOptEnum
import { FormInstance } from "element-plus";

// 表单参数
const fileProps = reactive<FormProps.Base<SysFile.SysFileInfo>>({
    opt: FormOptEnum.RENAME,
    record: {},
    disabled: false
});

const formRef = ref<FormInstance>();
const originalName = ref(""); // 旧文件名

// 表单验证规则
const rules = reactive({
    name: [
        {
            required: true,
            message: "请输入文件名",
            trigger: "blur"
        }
    ]
});

// 是否显示表单
const visible = ref(false);

function onOpen(props: FormProps.Base<SysFile.SysFileInfo>) {
    Object.assign(fileProps, props);
    originalName.value = fileProps.record["name"] || "";
    visible.value = true;
}

// 提交表单方法
const handleSubmit = () => {
    formRef.value?.validate(async valid => {
        if (!valid) {
            fileProps.record["name"] = originalName.value;
            return; //表单验证失败
        }

        // TODO: 调用文件上传API
        const formData = new FormData();
        for (const key in fileProps.record) {
            formData.append(key, fileProps.record[key]);
        }
        // 表单提交逻辑
        fileAPI
            .rename(formData)
            .then(() => {
                // 刷新表格数据
                if (fileProps.successful) {
                    fileProps.successful();
                }
            })
            .catch(() => {
                fileProps.record["name"] = originalName.value;
            })
            .finally(() => {
                // 提交成功后关闭表单
                onClose();
            });
    });
};

// 关闭表单方法
const onClose = () => {
    fileProps.record = {};
    visible.value = false;
};

// 暴露给父组件的方法
defineExpose({
    onOpen
});
</script>
